package dataDAOImpl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


import dataConnector.Connector;
import dataDAOInterfaces.DALException;
import dataDAOInterfaces.ICommodityBatchDAO;
import dataDTO.CommodityBatchDTO;

public class MySQLCommodityBatchDAO implements ICommodityBatchDAO {

	@Override
	public CommodityBatchDTO getCommodityBatch(int cbId) throws DALException {
		ResultSet rs = Connector.doQuery("SELECT*FROM raavarebatch WHERE rb_id = "+ cbId);
		try{
			if(!rs.first()) throw new DALException ("The commoditybatch "+ cbId + " dont exist");
			return new CommodityBatchDTO(rs.getInt(1),rs.getInt(2), rs.getDouble(3));
		}
		catch (SQLException e) {throw new DALException(e);}
	}

	@Override
	public List<CommodityBatchDTO> getCommodityBatchList() throws DALException {
		List<CommodityBatchDTO> list = new ArrayList<CommodityBatchDTO>();
		ResultSet rs = Connector.doQuery("SELECT*FROM raavarebatch");
		try{
			while(rs.next()){
				list.add(new CommodityBatchDTO(rs.getInt(1),rs.getInt(2),rs.getDouble(3)));
			}
		}
		catch (SQLException e){throw new DALException(e);}
		return list;
	}

	@Override
	public List<CommodityBatchDTO> getCommodityBatchList(int commodityId)
			throws DALException {
		List<CommodityBatchDTO> list = new ArrayList<CommodityBatchDTO>();
		ResultSet rs = Connector.doQuery("SELECT*FROM raavarebatch WHERE raavare_id = "+commodityId);
		try{
			while(rs.next())
			{
				list.add(new CommodityBatchDTO(rs.getInt(1), rs.getInt(2), rs.getDouble(3)));
			}
		}
		catch(SQLException e) {throw new DALException(e);}
		return list;
	}

	@Override
	public void createCommodityBatch(CommodityBatchDTO commoditybatch)
			throws DALException {
		Connector.doUpdate("INSERT INTO raavarebatch(rb_id,raavare_id,maengde) VALUES" +
				"(" + commoditybatch.getCbId() + ",'" + commoditybatch.getCommodityId() + "','" + commoditybatch.getVolume() + "')");
	}

	@Override
	public void updateCommodityBatch(CommodityBatchDTO commoditybatch)
			throws DALException {
		Connector.doUpdate("UPDATE raavarebatch SET rb_id = '" + commoditybatch.getCbId() + "', raavare_id = '" 
				+commoditybatch.getCommodityId() + "', maengde = " + commoditybatch.getVolume() + "WHERE rb_id = " + 
				commoditybatch.getCbId());
	}
}